<template>
  <div>
    <div>
      <h1>1、正常计算时间差（日期格式相同，具体到天数）</h1>
      <div>开始日期： <input type="date" v-model="date1" /></div>
      <div>结束日期： <input type="date" v-model="date2" /></div>
      时间差：{{dateDifference}}
    </div>
    <div>
      <h1>
        2、计算时间差，两日期日期格式不同（项目做过的计算入职多少天，两个日期格式不同，不够严谨的默认去年的今天到今年的今天为一年）
      </h1>
      {{ year }}年{{ days }}天
      <div>当前年{{ cunterndate }}</div>
      <div>入职年{{ regesteDate }}</div>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      date1: '0000-00-00',
      date2: '0000-00-00',
      cunterndate: "",
      regesteDate: "2017-10-09", //入职日期
      year: "0",
      days: "0",
    };
  },
  computed: {
    dateDifference() {
    return  this.getDifference();
    },
  },
  methods: {
    computeDays() {
      var date = new Date();
      let cunterndate = date.toLocaleDateString(); //当前日期
      this.cunterndate = cunterndate;
      let cuntyear = date.getFullYear(); //当前年
      var time = Date.parse(this.regesteDate);
      let resDate = new Date(time); //入职日期
      let resyear = resDate.getFullYear(); //入职年
      let resmonth = resDate.getMonth() + 1; //入职月
      let resdat = resDate.getDate(); //入职日
      let tempdate = cuntyear + "/" + resmonth + "/" + resdat; //标志日期
      let tempdate1 = Date.parse(tempdate);
      let cunterndate1 = Date.parse(cunterndate);
      if (cunterndate1 == tempdate1) {
        if (cuntyear - resyear > 0) {
          this.year = cuntyear - resyear; //刚好整年
        } else {
          this.year = 0;
        }
      } else if (cunterndate1 < tempdate1) {
        this.year = cuntyear - resyear - 1;
        let lastyear = cuntyear - 1; //当前年上一年
        let lastdate = lastyear + "/" + resmonth + "/" + resdat; //上一年标志日期
        let startDate = Date.parse(lastdate);
        let endDate = Date.parse(cunterndate);
        this.days = parseInt((endDate - startDate) / (1 * 24 * 60 * 60 * 1000));
      } else {
        this.year = cuntyear - resyear;
        let startDate = Date.parse(tempdate);
        let endDate = Date.parse(cunterndate);
        this.days = parseInt((endDate - startDate) / (1 * 24 * 60 * 60 * 1000));
      }

      //console.log(cunterndate);
    },
    getDifference() {
      var startDate=Date.parse(this.date1);
      var endDate=Date.parse(this.date2);
      var day=parseInt((endDate-startDate)/(24*60*60*1000))
      return day
    },
  },
  mounted() {
    this.computeDays();
  },
};
</script>